package com.luo.demo.common.interceptor;

import com.luo.demo.common.exception.BusinessException;
import com.luo.demo.common.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取 Token
        String token = request.getHeader("Authorization");

        // 验证 Token
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉 "Bearer " 前缀
            try {
                String username = jwtUtil.getUsernameFromToken(token);
                if (username != null && !jwtUtil.isTokenExpired(token)) {
                    // 将用户名存入请求属性中，方便后续使用
                    request.setAttribute("username", username);
                    return true;
                }
            } catch (Exception e) {
                throw new BusinessException(401, "Token 无效或已过期");
            }
        }

        // Token 无效
        throw new BusinessException(401, "请提供有效的 Token");
    }
}